using System;
using System.Runtime.InteropServices;

using WorkflowCommon = Scenario.WorkflowEngine.DataModel.Common;
using Scenario.WorkflowEngine.DataModel.WorkflowParticipantsData;

namespace Scenario.WAPI
{
	public partial class Role
	{
		public Role()
		{
		}

		public static bool CheckGrant(WorkflowCommon.XMLGrants xmlGrants, string sUser, string sGrantType)
		{
			WorkflowCommon.XMLGrant xmlGrant=null;

			bool bRetYes = true;
			bool bRetNo = false;

			for ( int i=0; i<xmlGrants.Count; i++)
			{
				xmlGrant = (WorkflowCommon.XMLGrant)xmlGrants[i];

				if ( xmlGrant.Type == sGrantType ) 
				{
					if ( xmlGrant.Enabled == WorkflowCommon.XMLGrant.YES_ENABLED ) 
					{
						try
						{
							xmlGrant.XMLUsers.GetUser (sUser);
							return true;
						}
                        catch (Scenario.WorkflowEngine.DataModel.Exception.UserNotFound)
						{
						}

						bool bNotInRole = true;
						XMLRole xmlRole = null;
						for ( int uiRole=0; uiRole<xmlGrant.XMLRoles.Count; uiRole++)
						{
							xmlRole = (XMLRole) xmlGrant.XMLRoles[uiRole];

							Response wapiResponse = new Response();
							string sRole = Role.GetRolesByKey (xmlRole.Key, ref wapiResponse);

							if ( wapiResponse.iCode == 0 )
							{
								XMLRole role = new XMLRole();
								role.Parse(sRole);

								try
								{
									role.XMLUsers.GetUser(sUser);
									bRetYes=true;
									bNotInRole=false;
								}
                                catch (Scenario.WorkflowEngine.DataModel.Exception.UserNotFound) 
								{
								}
							}
						}

						if ( bNotInRole )
							return false;
					}
					else
					{
						try
						{
							xmlGrant.XMLUsers.GetUser (sUser);
							return false;
						}
                        catch (Scenario.WorkflowEngine.DataModel.Exception.UserNotFound)
						{
						}

						XMLRole xmlRole = null;
						for ( int uiRole=0; uiRole<xmlGrant.XMLRoles.Count; uiRole++)
						{
							xmlRole = (XMLRole) xmlGrant.XMLRoles[uiRole];

							Response wapiResponse = new Response();
							string sRole = Role.GetRolesByKey (xmlRole.Key, ref wapiResponse);

							if ( wapiResponse.iCode == 0 )
							{
								XMLRole role = new XMLRole();
								role.Parse(sRole);

								try
								{
									role.XMLUsers.GetUser(sUser);
									bRetNo = true;
								}
                                catch (Scenario.WorkflowEngine.DataModel.Exception.UserNotFound) 
								{
								}
							}
						}
					}
				}
			}

			return bRetYes && !bRetNo;
		}
	}
}
